//
//  WXPProductPackageVC.m
//  MexicoLoan
//
//  Created by wxp on 2025/3/8.
//

#import "WXPProductPackageVC.h"
#import "WXPProductPackageTopSliderMoneyView.h"
#import "WXPProductPackageCell.h"
#import "WXPProductPackageFooterView.h"
#import "WXPLoanAgreementVC.h"
#import "WXPTotalLoanInfoVC.h"
#import "WXPSubmitOrderSuccessVC.h"


@interface WXPProductPackageVC ()

@property (nonatomic, strong) WXPNavView * navView;
@property (nonatomic, assign) BOOL immediatePop;
@property (nonatomic, strong) WXPTwoBtnPopUpWindowView * detainmentView;

@property (nonatomic, strong) UIView * headerView;
@property (nonatomic, strong) WXPProductPackageFooterView * footerView;
@property (nonatomic, strong) WXPProductPackageTopSliderMoneyView * topSliderMoneyView;

@property (nonatomic, strong) WXPCommonAgreementView * agreementView;
@property (nonatomic, strong) NSDictionary * deviceInfo;

@property (nonatomic, strong) NSArray * allArydatas;
@property (nonatomic, assign) double minValue;
@property (nonatomic, assign) double maxValue;
@property (nonatomic, assign) int totalPeriods;
@property (nonatomic, assign) int maxTerm;
@property (nonatomic,   copy) NSString * applyMoney;
@property (nonatomic,   copy) NSString * agreementHtml;
@property (nonatomic,   copy) NSString * startTime;

@end

@implementation WXPProductPackageVC

#pragma mark - lazy
- (WXPNavView *)navView
{
    if (_navView == nil) {
        _navView = [WXPNavView  new];
        [_navView resetViewWithTitle:@"Productos solicitados"];
        _navView.leftTop = XY(0, 0);
        WEAKSELF
        _navView.blockPop = ^{
            if(weakSelf.immediatePop){
                [Global_Nav popToRootViewControllerAnimated:true];
            }else{
                // 挽留弹窗
                weakSelf.immediatePop = true;
                [weakSelf.view addSubview:weakSelf.detainmentView];
            }
        };
    }
    return  _navView;
}
- (WXPTwoBtnPopUpWindowView *)detainmentView{
    if (!_detainmentView) {
        _detainmentView = [WXPTwoBtnPopUpWindowView new];
        ModelBtn * model = [ModelBtn new];
        model.title = @"Por favor, reconsidera, ¡la cuota del préstamo seguirá subiendo!";
        model.rightName = @"confirmar";
        model.isHide = false;
        [_detainmentView resetWithModel:model];
        [_detainmentView resetOnlyShowRightBtn];
        WEAKSELF
        _detainmentView.blockRightClick = ^{
            [weakSelf.detainmentView removeFromSuperview];
        };
    }
    return _detainmentView;
}
- (WXPCommonAgreementView *)agreementView{
    if (!_agreementView) {
        _agreementView = [WXPCommonAgreementView new];
        _agreementView.centerXBottom = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT-LEFT_MARDIN);
    }
    return _agreementView;
}
- (UIView *)headerView{
    if (_headerView == nil) {
        _headerView = [UIView  new];
    }
    return  _headerView;
}
- (WXPProductPackageFooterView *)footerView{
    if (!_footerView) {
        _footerView = [WXPProductPackageFooterView new];
        WEAKSELF
        _footerView.blockJumpToAgreement = ^{
            WXPLoanAgreementVC * vc = [WXPLoanAgreementVC new];
            vc.htmlStr = weakSelf.agreementHtml;
            [Global_Nav pushViewController:vc animated:true];
        };
        _footerView.blockJumpToTotalLoanInfo = ^{
            WXPTotalLoanInfoVC * vc = [WXPTotalLoanInfoVC new];
            vc.array = weakSelf.aryDatas;
            [Global_Nav pushViewController:vc animated:true];
        };
    }
    return _footerView;
}
- (WXPProductPackageTopSliderMoneyView *)topSliderMoneyView{
    if (_topSliderMoneyView == nil) {
        _topSliderMoneyView = [WXPProductPackageTopSliderMoneyView  new];
        [_topSliderMoneyView startCountdownTime];
        WEAKSELF
        _topSliderMoneyView.blockSliderValueChanged = ^(int value) {
            CGFloat result = value / 100.0;
            if(weakSelf.minValue < weakSelf.maxValue){
                double newMaxResult = (weakSelf.maxValue-weakSelf.minValue)*result+weakSelf.minValue;
                newMaxResult = round(newMaxResult/100) * 100;
                if(value == weakSelf.maxValue){
                    newMaxResult = weakSelf.maxValue;
                }
                if(value == weakSelf.minValue){
                    newMaxResult = weakSelf.minValue;
                }
                [weakSelf.topSliderMoneyView.labelMoney fitTitle:[GlobalMethod showMoney:strDot2F(newMaxResult)] variable:0];
                weakSelf.topSliderMoneyView.labelMoney.leftCenterY = weakSelf.topSliderMoneyView.labelMoney.leftCenterY;
                // 筛选数据
                [weakSelf filterData:newMaxResult];
            }
        };
        _topSliderMoneyView.blockApplyClick = ^{
            [weakSelf requestApply];
        };
    }
    return  _topSliderMoneyView;
}


#pragma mark - viewDidLoad
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.startTime = [GlobalMethod getTimeStampMillisecond];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_Products action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self checkUploadDeviceInfo];
    [self requestCreditInfo];
}
- (void)dealloc {
    [self.topSliderMoneyView endCountdownTime];
}

- (void)configUI{
    [self.tableView registerClass:[WXPProductPackageCell class] forCellReuseIdentifier:NSStringFromClass([WXPProductPackageCell class])];
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.viewBG.bounds;
    gradientLayer.colors = @[(id)COLOR_PRIMARY.CGColor, (id)COLOR_BACKGROUND.CGColor];
    gradientLayer.startPoint = CGPointMake(0.5, 0.0);
    gradientLayer.endPoint = CGPointMake(0.5, 1.0);
    [self.viewBG.layer insertSublayer:gradientLayer atIndex:0];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableHeaderTopBg.backgroundColor = [UIColor clearColor];
    self.tableView.height = self.agreementView.top-self.navView.bottom;
    [self.view addSubview:self.navView];
    [self.view addSubview:self.agreementView];
    [self resetHeaderView];
}

#pragma mark - resetHeaderView
- (void)resetHeaderView{
    self.headerView = [UIView initWithViews:@[
        self.topSliderMoneyView,
    ]];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
}

#pragma mark - UITableViewDelegate
//row num
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.aryDatas.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WXPProductPackageCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WXPProductPackageCell class]) forIndexPath:indexPath];
    [cell resetCellWithModel:self.aryDatas[indexPath.row]];
    WEAKSELF
    cell.blockOpenOrCloseDetail = ^(ModelProductPackageList * model) {
        // 获取借款金额、周期、利息，管理费等信息
        if (model.isShowDetail == false){
            [weakSelf requestLoanApplyDetailWithApplicationAmount:strDotF(model.amount) applicationTerm:strDotF(model.term) productId:strDotF(model.productPackageListIdentifier) termUnit:strDotF(model.termUnit) model:model];
        }else{
            model.isShowDetail = !model.isShowDetail;
            [weakSelf.tableView reloadData];
        }
    };
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [WXPProductPackageCell getHeight:self.aryDatas[indexPath.row] className:@"" selectorName:@"resetCellWithModel:"];
}
//table header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  nil;
}
//table footer
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

#pragma mark - request - 设备信息
// 检查是否需要上传扩展信息
- (void)checkUploadDeviceInfo{
    [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Check extInfo:nil];
    [RequestApi requestCheckUploadDeviceInfoWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        BOOL needUploadDeviceInfo   = [response boolValueForKey:KEY_deviceInfo];
        if(needUploadDeviceInfo){
            [self uploadDeviceInfo];
        }
        BOOL needUploadAddressBook  = [response boolValueForKey:KEY_addressBook];
        if(needUploadAddressBook){
            [self uploadAddressBookInfo];
        }
        BOOL needUploadCalendarInfo = [response boolValueForKey:KEY_calendarInfo];
        if(needUploadCalendarInfo){
            [self uploadCalendarInfo];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 上传设备信息
- (void)uploadDeviceInfo{
    NSMutableDictionary * authExtInfoDic = [NSMutableDictionary  new];
    if (isStr([GlobalData sharedInstance].Global_UserCode)) {
        [authExtInfoDic setObject:[GlobalData sharedInstance].Global_UserCode forKey:KEY_userId];
    }
    // 获取设备信息
    WEAKSELF
    [GlobalMethod getDeviceInfoBlock:^(NSDictionary *dict) {
        if ([weakSelf.deviceInfo count] && weakSelf.deviceInfo) {
            // 已获取设备信息，为防止接口频繁调用
        }else{
            weakSelf.deviceInfo = dict;
            // 需要上传设备信息
            if(weakSelf.deviceInfo != nil){
                [authExtInfoDic setObject:weakSelf.deviceInfo forKey:KEY_device_info];
                [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_DeviceInfo_Upload extInfo:nil];
                // 执行上传任务
                [RequestApi requestUploadExtInfoWithExtInfo:authExtInfoDic delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
                    [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_DeviceInfo_End extInfo:@{@"isSuccess": @"true", @"errorMsg": @""}];
                } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
                    [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_DeviceInfo_End extInfo:@{@"isSuccess": @"false", @"errorMsg": errorStr}];
                }];
            }
        }
    }];
}

// 上传通讯录
- (void)uploadAddressBookInfo{
    NSMutableDictionary * authExtInfoDic = [NSMutableDictionary  new];
    if (isStr([GlobalData sharedInstance].Global_UserCode)) {
        [authExtInfoDic setObject:[GlobalData sharedInstance].Global_UserCode forKey:KEY_userId];
    }
    // 获取通讯录
    [GlobalMethod getAddressBookAuthorityBlock:^{
        [GlobalMethod asynthicBlock:^{
            [GlobalMethod getAddressBookArrayBlock:^(NSMutableArray *array) {
                if(isAry(array)){
                    [authExtInfoDic setObject:array forKey:KEY_address_book];
                    // 执行上传任务
                    [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Contact_Upload extInfo:nil];
                    [RequestApi requestUploadExtInfoWithExtInfo:authExtInfoDic delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
                        
                    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
                        
                    }];
                }
            }];
        }];
    } isShowTips:false];
}

// 上传日历信息
- (void)uploadCalendarInfo{
    NSMutableDictionary * authExtInfoDic = [NSMutableDictionary  new];
    if (isStr([GlobalData sharedInstance].Global_UserCode)) {
        [authExtInfoDic setObject:[GlobalData sharedInstance].Global_UserCode forKey:KEY_userId];
    }
    // 获取日历信息
    [GlobalMethod getCalendarInfoBlock:^(NSMutableArray *array) {
        [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Calendar_Read extInfo:@{@"count": [NSString stringWithFormat:@"%ld", array.count]}];
        [authExtInfoDic setObject:(isAry(array))?array:@[] forKey:KEY_calendar_list];
        // 执行上传任务
        [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Calendar_Upload extInfo:nil];
        [RequestApi requestUploadExtInfoWithExtInfo:authExtInfoDic delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
            [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Calendar_End extInfo:@{@"isSuccess": @"true", @"errorMsg": @""}];
        } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
            [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Calendar_End extInfo:@{@"isSuccess": @"false", @"errorMsg": errorStr}];
        }];
    }];
}

#pragma mark - request
// 获取首页需要的用户信用额度
- (void)requestCreditInfo{
    [RequestApi requestCreditInfoWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        self.maxValue = [response doubleValueForKey:KEY_unused];
        [self.topSliderMoneyView resetMoney:response];
        
        // 风控埋点
        [GlobalMethod addRiskControlWithType:KEY_BEGIN_LOAN startTime:self.startTime endTime:[GlobalMethod getTimeStampMillisecond]];
        
        // 产品列表
        [self requestProductPackaging];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        // [self.customerLoadingView hideLoading];
    }];
}

// 产品列表 - 产品打包首页
- (void)requestProductPackaging{
    [self showLoadingView];
    [RequestApi requestProductPackaging3WithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        // 存本地
        self.allArydatas = [GlobalMethod exchangeDic:response toAryWithModelName:@"ModelProduct"];
        
//        [self.loadingView hideLoading];
        // 没有产品就直接返回
        if(!isAry(self.allArydatas)){
//            [self.customerLoadingView hideLoading];
            [Global_Nav popToRootViewControllerAnimated:true];
            return;
        }
        
        // 筛选数据
        [self filterData:self.maxValue];
        
        // 获取最小值
        ModelProduct * model = self.allArydatas.firstObject;
        double amount = model.amount;
        for (ModelProduct * model in self.allArydatas) {
            if(model.amount <= amount){
                amount = model.amount;
            }
        }
        self.minValue = amount;
        if (self.minValue >= self.maxValue){
            self.topSliderMoneyView.customSlider.userInteractionEnabled = false;
        }
        [self.topSliderMoneyView.labelMinMoney fitTitle:[NSString stringWithFormat:@"$ %@",[GlobalMethod showMoney:strDot2F(amount)]] variable:0];
        self.topSliderMoneyView.labelMinMoney.leftCenterY = self.topSliderMoneyView.labelMinMoney.leftCenterY;
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        [self.loadingView hideLoading];
    }];
}

// 筛选数据
- (void)filterData:(double)maxValue{
    [self showLoadingView];
    
    self.applyMoney = strDotF(maxValue);
    double closestNumber = INT_MIN;
    double diff = INT_MAX;
    ModelProduct * markModel = [ModelProduct new];
    for (ModelProduct *model in self.allArydatas) {
        if(model.amount <= maxValue){
            double currentDiff = fabs(self.maxValue - model.amount);
            if (currentDiff < diff) {
                closestNumber = model.amount;
                diff = currentDiff;
                markModel = model;
            }
        }
    }
    [self.aryDatas removeAllObjects];
    [self.aryDatas addObjectsFromArray:markModel.productPackageList];
    
    [self.topSliderMoneyView.labelSectionTitle fitTitle:[NSString stringWithFormat:@"Mi cartera de %@",(self.aryDatas.count>1 ? @"productos" : @"productos")] variable:0];
    self.topSliderMoneyView.labelSectionTitle.leftCenterY = self.topSliderMoneyView.labelSectionTitle.leftCenterY;
    
    [self.tableView reloadData];
    [self.loadingView hideLoading];
//    [self.customerLoadingView hideLoading];
    
    // 获取借款协议HTML配置信息
    [self requestContractLoanHtmlInfo];
}

// 获取借款金额、周期、利息，管理费，利率等信息接口
- (void)requestLoanApplyDetailWithApplicationAmount:(NSString *)applicationAmount applicationTerm:(NSString *)applicationTerm productId:(NSString *)productId termUnit:(NSString *)termUnit model:(ModelProductPackageList *)model{
    [RequestApi requestLoanApplyDetailWithApplicationAmount:applicationAmount applicationTerm:applicationTerm productId:productId termUnit:termUnit delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        NSMutableArray * list = [NSMutableArray arrayWithArray:[GlobalMethod exchangeDic:response[KEY_pairs] toAryWithModelName:@"ModelPairs"]];
        model.pairs = list;
        model.isShowDetail = !model.isShowDetail;
        [self.tableView reloadData];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 获取借款协议参数
- (void)requestContractLoanHtmlInfo{
    NSMutableArray * reqList = [NSMutableArray new];
    for (ModelProductPackageList * model in self.aryDatas) {
        NSDictionary * dic = @{
            KEY_amount: strDotF(model.amount),
            KEY_id: strDotF(model.productPackageListIdentifier),
            KEY_term: strDotF(model.term),
        };
        [reqList addObject:dic];
    }
    [RequestApi requestContractLoanHtmlInfoWithReqList:reqList delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        int term = [response intValueForKey:KEY_term];
        NSString * apr = [response stringValueForKey:KEY_apr];
        NSString * repaymentPlanTime = [response stringValueForKey:KEY_repaymentPlanTime];
        repaymentPlanTime = [GlobalMethod exchangeTimestamp:repaymentPlanTime formate:TIME_DAY_MONTH_YEAR];
        int loanAmount = [response intValueForKey:KEY_loanAmount];
        int actualAmount = [response intValueForKey:KEY_actualAmount];
        NSString * termUnitStr = @"Días";
        self.agreementHtml = [NSString stringWithFormat:@"/contract/loan.html?term=%d%@&apr=%@&repaymentPlanTime=%@&loanAmount=%@&actualAmount=%@",term, termUnitStr, readStr(apr), readStr(repaymentPlanTime), [GlobalMethod showMoney:[NSString stringWithFormat:@"%d",loanAmount]], [GlobalMethod showMoney:[NSString stringWithFormat:@"%d",actualAmount]]];
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 申请借款
- (void)requestApply{
    NSString * startTime = [GlobalMethod getTimeStampMillisecond];
    double allProductMoney = 0.00;
    NSMutableArray * array = [NSMutableArray array];
    for (ModelProductPackageList * model in self.aryDatas) {
        NSDictionary * dic = @{
            KEY_applyAmount: strDotF(model.amount),
            KEY_isReloan: strDotF(model.isReloan),
            KEY_productId: strDotF(model.productPackageListIdentifier),
            KEY_term: strDotF(model.term),
            KEY_termUnit: strDotF(model.termUnit)
        };
        [array addObject:dic];
        allProductMoney = allProductMoney + model.amount;
    }
    
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_Products action:KEY_Apply_Loan_Click extInfo:@{@"applyMoney": self.applyMoney, @"allProductMoney": strDotF(allProductMoney)}];
    
    [RequestApi requestApplyWithAry:array delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {

        [GlobalMethod hitPointWithPageName:KEY_Products action:KEY_Apply_Loan_Success extInfo:nil];
        // 风控埋点
        [GlobalMethod addRiskControlWithType:KEY_END_LOAN startTime:startTime endTime:[GlobalMethod getTimeStampMillisecond]];
        
        
        // 申请成功
        WXPSubmitOrderSuccessVC * vc = [WXPSubmitOrderSuccessVC new];
        BOOL isShowMark = [response[RESPONSE_DATA] boolValue];
        vc.isShowScoreView = isShowMark;
        [Global_Nav pushViewController:vc animated:true];

    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {

    }];
}

@end
